package com.swn.common.util;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.sql.Blob;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONObject;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * 项目工具类
 * 
 */
public class Util {

	@SuppressWarnings("unused")
	private static final Log logger = LogFactory.getLog(Util.class);

	/**
	 * 得到型如：2010-02-03 01:02:16 的时间
	 * 
	 * @return
	 */
	public static String getDateAndTime() {
		Calendar cal = Calendar.getInstance();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return formatter.format(cal.getTime());
	}

	/**
	 * 
	 * @Title: getDateAndTime1
	 * @Description: TODO(获取除秒的时间)
	 * @param @return 设定文件
	 * @return String 返回类型
	 * @author chenql
	 * @date 2016-1-12 下午2:26:15
	 * @throws
	 */
	public static String getDateAndTime1() {
		Calendar cal = Calendar.getInstance();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		return formatter.format(cal.getTime());
	}

	/**
	 * 
	 * @Title: getTime
	 * @Description: TODO(获取时分)
	 * @param @return 设定文件
	 * @return String 返回类型
	 * @author chenql
	 * @date 2016-1-12 下午2:26:31
	 * @throws
	 */
	public static String getTime() {
		Calendar cal = Calendar.getInstance();
		SimpleDateFormat formatter = new SimpleDateFormat("HH:mm");
		return formatter.format(cal.getTime());
	}

	/**
	 * 根据当前日期获得其它日期
	 * 
	 * @param counter
	 *            ：度量。如果得到昨天，则counter=-1.
	 * @return
	 */
	public static String getDateDepdNow(int counter) {
		Calendar cal = Calendar.getInstance();
		cal.add(Calendar.DATE, counter);
		Date d = cal.getTime();
		SimpleDateFormat sp = new SimpleDateFormat("yyyy-MM-dd");
		return sp.format(d);// 获取昨天日期
	}

	/**
	 * 获取当前日期加上一个月后的日期
	 * 
	 * @param counter
	 *            ：所加的月数
	 * @return
	 */
	public static String getDateDepdNowMonth(int counter) {
		Calendar cal = Calendar.getInstance();
		cal.add(Calendar.MONTH, counter);
		Date d = cal.getTime();
		SimpleDateFormat sp = new SimpleDateFormat("yyyy-MM-dd");
		return sp.format(d);
	}

	/**
	 * 获取当前月份加上传入月数时间的当月最后一天日期 如：2013-11-3 传入2 --> 2014-1-31
	 * 
	 * @param counter
	 * @return
	 */
	public static String getDateAddMonth(int counter) {
		Calendar cal = Calendar.getInstance();
		cal.set(Calendar.DAY_OF_MONTH, 1);
		cal.add(Calendar.MONTH, counter);
		cal.roll(Calendar.DAY_OF_MONTH, -1);
		Date d = cal.getTime();
		SimpleDateFormat sp = new SimpleDateFormat("yyyy-MM-dd");
		return sp.format(d);
	}

	/**
	 * 获得 下个月的第一天
	 * 
	 * @return
	 */
	public static String getDateNext() {
		Calendar cal = Calendar.getInstance();
		cal.add(Calendar.MONTH, 1);
		cal.set(Calendar.DAY_OF_MONTH, 1);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		return sdf.format(cal.getTime());
	}

	/**
	 * 根据当前日期获得一定格式的其他日期
	 * 
	 * @param counter
	 *            度量。如果得到昨天，则counter=-1.
	 * @param formatStr
	 * @return
	 */
	public static String getDateDepdNow(int counter, String formatStr) {
		Calendar cal = Calendar.getInstance();
		cal.add(Calendar.DATE, counter);
		Date d = cal.getTime();
		SimpleDateFormat sp = new SimpleDateFormat(formatStr);
		return sp.format(d);// 获取昨天日期
	}

	/**
	 * 获取输入日期的下一天 返回 8位 like 20050101
	 * 
	 * @param today
	 * @return
	 */
	public static String getNextDay(String day) {
		return getNextDay(day, 1);
	}

	/**
	 * 获取输入日期的下 n 天 返回 8位 like 20050101
	 * 
	 * @param day
	 * @param n
	 * @return
	 */
	public static String getNextDay(String day, int n) {
		if (day == null || "".equals(day) || day.length() != 8) {
			throw new RuntimeException("由于缺少必要的参数，系统无法进行制定的日期换算.");
		}
		try {
			String sYear = day.substring(0, 4);
			int year = Integer.parseInt(sYear);
			String sMonth = day.substring(4, 6);
			int month = Integer.parseInt(sMonth);
			String sDay = day.substring(6, 8);
			int dday = Integer.parseInt(sDay);
			Calendar cal = Calendar.getInstance();
			cal.set(year, month - 1, dday);
			cal.add(Calendar.DATE, n);
			SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
			return df.format(cal.getTime());

		} catch (Exception e) {
			throw new RuntimeException("进行日期运算时输入得参数不符合系统规格." + e);

		}
	}
	
	
	/**
	 * 基于某天+-一定天数获取新的日期
	 * @param day 格式为：yyyy-MM-dd
	 * @param n
	 * @return
	 */
	public static String getNextDayByDate(String day, int n) {
		if (day == null || "".equals(day) || day.length() != 10) {
			throw new RuntimeException("由于缺少必要的参数，系统无法进行制定的日期换算.");
		}
		try {
			String sYear = day.substring(0, 4);
			int year = Integer.parseInt(sYear);
			String sMonth = day.substring(5, 7);
			int month = Integer.parseInt(sMonth);
			String sDay = day.substring(8, 10);
			int dday = Integer.parseInt(sDay);
			Calendar cal = Calendar.getInstance();
			cal.set(year, month - 1, dday);
			cal.add(Calendar.DATE, n);
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
			return df.format(cal.getTime());

		} catch (Exception e) {
			throw new RuntimeException("进行日期运算时输入得参数不符合系统规格." + e);

		}
	}
	
	/**
	 * 校验字符串是否为 simpleDateFormatStr 规定的格式
	 * 
	 * @param str
	 * @param simpleDateFormatStr :日期格式   如"yyyy-MM-dd"
	 * @return boolean
	 *
	 * @Author taozhaocai
	 * @Date 2016年7月29日 下午7:05:54
	 */
	public static boolean isValidDate(String str,String simpleDateFormatStr) {
        boolean convertSuccess=true;
        // 指定日期格式为四位年/两位月份/两位日期，注意yyyy/MM/dd区分大小写；
         SimpleDateFormat format = new SimpleDateFormat(simpleDateFormatStr);
         try {
        	 // 设置lenient为false. 否则SimpleDateFormat会比较宽松地验证日期，比如2007/02/29会被接受，并转换成2007/03/01
            format.setLenient(false);
            format.parse(str);
         } catch (ParseException e) {
           // e.printStackTrace();
 // 如果throw java.text.ParseException或者NullPointerException，就说明格式不对
            convertSuccess=false;
        } 
        return convertSuccess;
 }


	/**
	 * 得到UUID
	 * 
	 * @return 型如：cd6214f8-69fc-4e4b-be4a-c49e2f00f41 然后去掉-
	 */
	public static String createUUID() {
		String uuid = java.util.UUID.randomUUID().toString().replace("-", "");
		return uuid;
	}

	public static String trim(String value) {
		return value == null ? "" : value.trim();
	}

	/**
	 * 获得资源文件所在路径
	 * 
	 * @return
	 */
	public String getsourcePath() {
		return (this.getClass().getClassLoader().getResource("/").getPath()).replaceAll("%20", " ");
	}

	/**
	 * 获得属性文件内的某一属性
	 * 
	 * @param propertyName
	 * @return
	 */
	public String getProperty(String propertyName) {
		InputStream in = null;
		Properties p = new Properties();
		String path = (this.getClass().getClassLoader().getResource("/").getPath() + "sys.properties").replaceAll("%20", " ");
		try {
			in = new BufferedInputStream(new FileInputStream(path));
			p.load(in);
			return getUTF8Content(p.getProperty(propertyName));
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (in != null)
				try {
					in.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
		}
		return "";
	}

	/**
	 * 获得log4j属性
	 * 
	 * @param propertyName
	 * @return
	 */
	public String getLog4jProperty(String propertyName) {
		InputStream in = null;
		Properties p = new Properties();
		String path = (this.getClass().getClassLoader().getResource("/").getPath() + "log4j.properties").replaceAll("%20", " ");
		try {
			in = new BufferedInputStream(new FileInputStream(path));
			p.load(in);
			return getUTF8Content(p.getProperty(propertyName));
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (in != null)
				try {
					in.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
		}
		return "";
	}

	/**
	 * 得到属性内容，并转化为utf-8编码
	 * 
	 * @param value
	 * @return
	 */
	public String getUTF8Content(String value) {
		String returnValue = value == null ? "" : value;
		// try {
		// returnValue = new String(returnValue.getBytes("iso-8859-1"),
		// "utf-8");
		// } catch (UnsupportedEncodingException e) {
		// }
		return returnValue;
	}

	private static String AmtFmt = "#,##0.00####";

	/**
	 * 将金额转化成按千分位的显示格式
	 * 
	 * @parm double 金额
	 * @return String 显示字符串
	 */
	public static String amtTranShow(double amt) {
		DecimalFormat df = new DecimalFormat(AmtFmt);
		return df.format(amt);
	}

	/**
	 * 
	 * 提供精确的小数位四舍五入处理。
	 * 
	 * @param v
	 *            需要四舍五入的数字
	 * @param scale
	 *            小数点后保留几位
	 * @return 四舍五入后的结果
	 * 
	 */
	public static double round(double v, int scale) {
		if (scale < 0) {
			throw new IllegalArgumentException("The scale must be a positive integer or zero");
		}
		BigDecimal b = new BigDecimal(Double.toString(v));
		BigDecimal one = new BigDecimal("1");
		return b.divide(one, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
	}

	/**
	 * 把double类型数保留2为小数然后转化为字符串，如果像1转化后为1.0，则后面要补全0.
	 * 
	 * @param v
	 * @return
	 */
	public static String roundTowPointStr(double v) {
		String dataStr = round(v, 2) + "";
		int location = dataStr.indexOf(".");
		String xiaoshu = dataStr.substring(location + 1);
		int l = xiaoshu.length();
		return l == 2 ? dataStr : dataStr + "0";
	}

	/**
	 * 把字符串中字符替换为另一字符：（可以替换特殊字符，如把'|'替换为空格。
	 * 
	 * @param str
	 * @param olderC
	 * @param newC
	 * @return
	 */
	public static String replaceChar(String str, char olderC, char newC) {
		StringBuffer returnStr = new StringBuffer();
		char[] ay = Util.trim(str).toCharArray();
		for (int i = 0; i < ay.length; i++) {
			char c = ay[i];
			if (c == olderC)
				returnStr.append(newC);
			else
				returnStr.append(c);
		}
		return returnStr.toString();
	}

	/**
	 * 把字符串中的多个空格压缩为1个空格
	 * 
	 * @param str
	 * @return
	 */
	public static String pressSpaceStr(String str) {
		return Util.trim(str).replaceAll(" {2,}", " ");
	}

	/**
	 * 传入日期与当前日期相减，返回天数
	 * 
	 * @param date
	 * @return
	 */
	public static long dateSubtraction(String date) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date date1;
		long num = 0;
		try {
			date1 = sdf.parse(date);
			Date endTime = new Date();
			num = (endTime.getTime() - date1.getTime()) / (24 * 60 * 60 * 1000) > 0 ? (endTime.getTime() - date1.getTime()) / (24 * 60 * 60 * 1000) : (date1.getTime() - endTime.getTime()) / (24 * 60 * 60 * 1000);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return num;
	}

	/**
	 * 提取字符串中的数字
	 * 
	 * @param str
	 * @return
	 */
	public static String getDigStr(String str) {
		return Util.trim(str).replaceAll("[^0-9]", "");
	}

	/**
	 * 判断某一个字符为汉字
	 * 
	 * @param c
	 * @return
	 */
	public static final boolean isChinese(char c) {
		Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
		if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {
			return true;
		}
		return false;
	}

	/**
	 * 判断是否为手机号
	 * 
	 * @param phone
	 * @return
	 */
	public static boolean judgePhoneNum(String phone) {
		Pattern p = Pattern.compile("1\\d{10}");
		Matcher m = p.matcher(phone);
		return m.matches();
	}

	/**
	 * PO对象转化为JSONObject
	 * 
	 * @param po
	 * @param prefixName
	 *            key前缀
	 * @return 注意：如果需要转化的自动较少，可以直接写：obj.accumulate("po.name", po.getName());
	 *         obj.accumulate("po.remark", po.getRemark());……
	 *         如较多，则可以调用该方法，但要保证没有大字段；可以重载该方法，包括哪些属性转化，哪些不转化
	 */
	public static JSONObject po2JsonObjPrefixName(Object po, String prefixName) {
		JSONObject obj = new JSONObject();
		Field[] fields = po.getClass().getDeclaredFields();// 当前类属性数组
		Field[] fieldsSuper = null;// 父类的属性数组
		if (po.getClass().getSuperclass() != null) {// 如果此类存在父类，则获取父类的属性数组
			fieldsSuper = po.getClass().getSuperclass().getDeclaredFields();
		}
		obj = po2JsonObjPrefixName(fields, obj, po, prefixName);// 对传入的类加前缀
		if (0 < fieldsSuper.length) {
			obj = po2JsonObjPrefixName(fieldsSuper, obj, po, prefixName);// 对传入的类的父类加前缀
		}
		return obj;
	}

	/**
	 * 通过java反射机制获取Java类的属性及属性值
	 */
	public static JSONObject po2JsonObjPrefixName(Field[] fields, JSONObject obj, Object po, String prefixName) {
		StringBuffer keyStr = new StringBuffer();
		for (int i = 0, len = fields.length; i < len; i++) {// 获取当前类的属性及属性值并实现转换
			try {
				String varName = fields[i].getName();
				boolean accessFlag = fields[i].isAccessible();
				fields[i].setAccessible(true);
				Object value = fields[i].get(po);
				if (value instanceof Blob) {// 如果数据类型为Blob类型，则进行转换;instanceof判断某个对象是否是某个类型的实例
					Blob blob = (Blob) value;
					value = new String(blob.getBytes((long) 1, (int) blob.length()));
				}
				keyStr.append(prefixName).append(".").append(varName);
				obj.accumulate(keyStr.toString(), value);
				keyStr.delete(0, keyStr.length());
				fields[i].setAccessible(accessFlag);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return obj;
	}

	/**
	 * 处理HTML标记，将"\n"转换为"<br>
	 * ",将"\r"转换为"<br>
	 * " 将" "转化为"&nbsp;"
	 * 
	 * @param 处理前的字符串str
	 * @return 处理后的字符串
	 */
	public static String returnToBr(String str) {
		if (str == null || str.equals(""))
			return str;
		else {
			str = str.replaceAll("\r\n", "<br>");
			str = str.replaceAll("\n", "<br>");
		}

		return str.replaceAll(" ", "&nbsp;");
	}

	/**
	 * 处理HTML标记，将"<"转换为"&lt;",将">"转换为"&gt;"
	 * 
	 * @param str
	 *            处理前的字符串
	 * @return string 处理后的字符串
	 */
	public static String returnToHTML(String str) {
		if (str == null || str.equals(""))
			return str;
		StringBuffer sTmp = new StringBuffer();
		int i = 0;
		while (i <= str.length() - 1) {
			if (str.charAt(i) == '<') {
				sTmp = sTmp.append("&lt;");
			} else if (str.charAt(i) == '>') {
				sTmp = sTmp.append("&gt;");
			} else
				sTmp = sTmp.append(str.substring(i, i + 1));
			i++;
		}
		String s2;
		s2 = sTmp.toString();
		return s2;
	}

	/**
	 * 判断字符串是否为空
	 * 
	 * @param text
	 */
	public boolean ifIsNull(String text) {
		boolean flag = false;

		if (text != null && !"".equals(text)) {
			flag = true;
		} else {
			flag = false;
		}
		return flag;
	}

	/**
	 * 获取工作流中每个环节对应的url
	 * 
	 * @param processtype
	 *            流程类型
	 * @param seque
	 *            环节名称
	 * @param processcode
	 *            流程编号
	 * @author Dsm
	 * @date 2015-09-02
	 */
	public static String processUrl(long processtype, long seque, String processcode) {
		String url = "";
		seque++;
		// ORDERLIFEHELP{public String label() {return "运营机构生活帮助工单"; }},
		// ORDERSERVE{public String label() {return "运营机构客服工单"; }},
		// ORDERURGENCY{public String label() {return "运营机构紧急救援工单"; }},
		// YUNYINGORDERREG{public String label() {return "运营机构工单登记"; }},
		// SERVICEORGANORDERLIFEHELP{public String label() {return "服务机构生活帮助工单";
		// }},
		// SERVICEORDERREG{public String label() {return "服务机构工单登记"; }},
		// ARCHIVESEXAM{public String label() {return "档案审核"; }},
		// KNOWLEDGEEXAM{public String label() {return "知识库审核"; }},
		// ORDERMONEYEXAM{public String label() {return "工单费用审核"; }};
		if (processtype == 0) { // 运营机构生活帮助工单
			// 1:新建工单 2:派单 3:派人 4:确认工单 5:回访
			if (seque == 1)
				url = "50,登记工单,jjyl/callcenter/lifehelp/saveLifeHelper.jsp";
			else if (seque == 2)
				url = "52,待派工单,jjyl/callcenter/lifehelp/dispatchLifeHelpOrder.jsp";
			else if (seque == 3)
				url = "174,待派工单,jjyl/serviceOrganization/orderManager/orderSend.jsp";
			else if (seque == 4)
				url = "242,派单确认,jjyl/callcenter/lifehelp/sureOrder.jsp";
			else if (seque == 5)
				url = "54,回访工单,jjyl/callcenter/lifehelp/replayOrder.jsp";
		} else if (processtype == 1) { // 运营机构客服工单
			// 1:新建工单 2:派单 3:处理工单 4:回访
			if (seque == 1)
				url = "15,录入工单,jjyl/callcenter/custorder/saveOrder.jsp";
			else if (seque == 2)
				url = "17,待派工单,jjyl/callcenter/custorder/waitOrder.jsp";
			else if (seque == 3)
				url = "18,待处理工单,jjyl/callcenter/custorder/pendingOrder.jsp";
			else if (seque == 4)
				url = "19,待回访工单,jjyl/callcenter/custorder/returningOrder.jsp";
		} else if (processtype == 2) { // 运营机构紧急救援工单
			// 1:救援工单 2:回访
			if (seque == 1)
				url = "304,录入工单,jjyl/callcenter/urgencyrescue/saveUrgencyRescue.jsp";
			else if (seque == 2)
				url = "305,回访工单,jjyl/callcenter/urgencyrescue/returnUrgencyRescue.jsp";

		} else if (processtype == 3) { // 运营机构工单登记
			// 1:工单登记 2:回访
			if (seque == 1)
				url = "51,录入工单,jjyl/callcenter/lifehelp/lifeHelperOrderReg.jsp";
			else if (seque == 2)
				url = "54,回访工单,jyl/callcenter/lifehelp/replayOrder.jsp";
		} else if (processtype == 4) { // 服务机构生活帮助工单
			// 1:新建工单 2:派人 3:确认工单 4:回访
			if (seque == 1)
				url = "241,登记工单,jjyl/serviceOrganization/orderManager/buildOrganizeOrder.jsp";
			else if (seque == 2)
				url = "174,待派工单,jjyl/serviceOrganization/orderManager/orderSend.jsp";
			else if (seque == 3)
				url = "242,派单确认,jjyl/callcenter/lifehelp/sureOrder.jsp";
			else if (seque == 4)
				url = "54,回访工单,jjyl/callcenter/lifehelp/replayOrder.jsp";
		} else if (processtype == 5) { // 服务机构工单登记
			// 1:工单登记 2:回访
			if (seque == 1)
				url = "262,录入工单,jjyl/serviceOrganization/orderManager/organizeOrderReg.jsp";
			else if (seque == 2)
				url = "54,回访工单,jjyl/callcenter/lifehelp/replayOrder.jsp";
		} else if (processtype == 6) { // 档案审核
			// 1:档案待审核 2:档案审核 这里 环节连接同一页面，档案里面分机构和老年人两种档案，根据流程编号区分
			if (processcode.contains("SO")) { // 机构档案
				url = "113,服务机构档案审核,jjyl/serviceaged/archives/serveOrgancheck.jsp";
			} else {
				url = "342,老年人档案审核,jjyl/serviceaged/archives/oldPeopleFilescheck.jsp";
			}
		} else if (processtype == 7) { // 知识库审核
			// 1:知识库待审核 2:知识库审核 1,2环节连接同一页面
			url = "341,知识审批,jjyl/knowledge/knowledgeManager/knowledgeCheck.jsp";
		} else if (processtype == 8) { // 工单费用审核
			// 1:工单费用待审核 2:工单费用审核 1,2环节连接同一页面
			url = "316,工单审核,jjyl/callcenter/examcharge/orderExam.jsp";
		}
		return url;
	}

	/**
	 * @Title: getProcesscode
	 * @Description: TODO 生成流程编号
	 * @param @param string
	 * @param @return
	 * @return String
	 * @throws
	 */
	public static String getProcesscode(String string) {
		Calendar cal = Calendar.getInstance();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmssSSS");
		return string + formatter.format(cal.getTime());
	}

	/**
	 * @Title: getProcesscode
	 * @Description: TODO 获取tomcat的路径用于图片上传
	 * @param @return
	 * @return String
	 * @throws
	 */
	public static void gettomcatpath() {
		File file = new File("WebRoot\\images\\uploadImages");

		try {
			System.out.println(file.getAbsolutePath());

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}


	/**功能说明:<此处是项目功能>
	 *	
	 * @author  : Leon
	 * @date    : 2016-5-6 下午4:39:07
	 * @modifier: 
	 * @mod_Date: 
	 * @return
	 */
	public static String getDay() {
		Calendar cal = Calendar.getInstance();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
		return formatter.format(cal.getTime());
	}
	/** 
	 * 方法名称:map转字符串 
	 * 传入参数:map 
	 * 返回值:String 形如 username'chenziwen^password'1234 
	*/  
	public static String transMapToString(Map map){  
	  java.util.Map.Entry entry;  
	  StringBuffer sb = new StringBuffer();  
	  for(Iterator iterator = map.entrySet().iterator(); iterator.hasNext();)  
	  {  
	    entry = (java.util.Map.Entry)iterator.next();  
	      sb.append(entry.getKey().toString()).append( "'" ).append(null==entry.getValue()?"":  
	      entry.getValue().toString()).append (iterator.hasNext() ? "^" : "");  
	  }  
	  return sb.toString();  
	} 
	/** 
	 * 方法名称:字符串转map
	 * 传入参数:mapString 形如 username'chenziwen^password'1234 
	 * 返回值:Map 
	*/  
	public static Map transStringToMap(String mapString){  
	  Map map = new HashMap();  
	  java.util.StringTokenizer items;  
	  for(StringTokenizer entrys = new StringTokenizer(mapString, "^");entrys.hasMoreTokens();   
	    map.put(items.nextToken(), items.hasMoreTokens() ? ((Object) (items.nextToken())) : null))  
	      items = new StringTokenizer(entrys.nextToken(), "'");  
	  return map;  
	}  
	/**
	 * 获取请求头中的IP地址信息
	 * @param request
	 * @return
	 */
	/*public static String getRequestIP(HttpServletRequest request){
		if(request.getHeader("x-forwarded-for")==null){
			return request.getRemoteAddr();
		}
		return request.getHeader("x-forwarded-for");
	}*/

}
